package my.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;

/**
 * ZIP工具类,主要用于打ZIP包
 * 注:在linux或非中文系统中可能出现中文文件名乱码,请做相应修改.
 * @author loyal
 * @version v1.0 2012-4-12 下午06:39:17
 */
public class ZipFileUtil {
	public void zipOnePack(String source, String zipPath) {
		try {
			File sourceFile = new File(source);
			File zipFile = new File(zipPath);
			zipOnePack(sourceFile, zipFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void zipOnePack(File sourceFile, File zipFile) {
		try {
			if (!sourceFile.exists())
				return;
			ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP,
					new FileOutputStream(zipFile));
			ZipArchiveOutputStream zos = (ZipArchiveOutputStream) aos;
			zos.setEncoding("GBK");
			zos.putArchiveEntry(new ZipArchiveEntry(sourceFile.getName()));
			IOUtils.copy(new FileInputStream(sourceFile), zos);
			zos.closeArchiveEntry();
			zos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void zipPack(List<File> sourceFiles, File zipFile) {
		try {
			if (sourceFiles.size() == 0)
				return;
			ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP,
					new FileOutputStream(zipFile));
			ZipArchiveOutputStream zos = (ZipArchiveOutputStream) aos;
			zos.setEncoding("GBK");
			for (File sourceFile : sourceFiles) {
				zos.putArchiveEntry(new ZipArchiveEntry(sourceFile.getName()));
				IOUtils.copy(new FileInputStream(sourceFile), zos);
				zos.closeArchiveEntry();
			}
			zos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void zipPack(List<String> sourcePaths, String zipPath) {
		try {
			List<File> sourceFiles = new ArrayList<File>();
			for (String sourcePath : sourcePaths) {
				sourceFiles.add(new File(sourcePath));
			}
			File zipFile = new File(zipPath);
			zipPack(sourceFiles, zipFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
